import 'dart:async';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:shopping_group/baseblocs/bloc_provider.dart';
import 'package:shopping_group/http/apis/apis.dart';
import 'package:shopping_group/http/http_request_all.dart';
import 'package:shopping_group/modle/main/entity/commo_spec4app_record_entity.dart';
import 'package:shopping_group/utils/network_utils.dart';
import 'package:shopping_group/utils/route_util.dart';

class MoreFuGoodPlayBloc implements BlocBase {
  List<CommoSpec4AppRecordEntity> _list = [];
  StreamController<Object> _initController = StreamController<Object>();
  StreamSink get initDate => _initController.sink;

  StreamController<Object> _addController = StreamController<Object>();
  StreamSink get _addDate => _addController.sink;
  Stream<Object> get sendData => _addController.stream;

  MoreFuGoodPlayBloc() {
    _initController.stream.listen(initData);
  }

  void initData(data) {
    if (data is Map) {
      _initTask(data);
    }
  }

  void _initTask(data) async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext)
        .requestFocus(FocusNode());
    BotToast.showLoading();
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.showText(text: '网络无法连接');
      } else {
        HttpUtilAll.post(Apis.FU_GOOD_URL, data: data, headers: {},
            success: (result) {
          BotToast.closeAllLoading();
          if (null != result) {
            List list = List.from(result);
            list.forEach((element) {
              CommoSpec4AppRecordEntity params =
                  CommoSpec4AppRecordEntity.fromJson(element);
              _list.add(params);
            });
            _addDate.add(_list);
          }
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  @override
  void dispose() {
    _initController?.close();
    _addController?.close();
  }
}
